package com.baishancloud.log.analyzer.model

import scala.io.Source

object MediaTypes {
  /**
   * 加载csv文件，将内容转化为map表
   *
   * @param path csv文件路径
   * @return
   */
  private def loadCsv(path: String): Map[String, Int] = {
    Source.fromInputStream(getClass.getResourceAsStream(path))
      .getLines()
      .map { line =>
        val splits = line.split(",")
        val id = splits(0).toInt
        val name = splits(1).toLowerCase()
        name -> id
      }
      .toMap
  }

  /**
   * 子类型名称和id对应关系map表
   */
  private val subtypeIdMaps = Vector[Map[String, Int]](
    Map(), // empty map that holds the index 0
    loadCsv("/application.csv"),
    loadCsv("/audio.csv"),
    loadCsv("/font.csv"),
    loadCsv("/image.csv"),
    loadCsv("/message.csv"),
    loadCsv("/model.csv"),
    loadCsv("/multipart.csv"),
    loadCsv("/text.csv"),
    loadCsv("/video.csv")
  )

  /**
   * 类型名称和id对应表，从1开始，每个类型下的子类型从csv文件中获取
   */
  private val typeIdMap = Map(
    "application" -> 1,
    "audio" -> 2,
    "font" -> 3,
    "image" -> 4,
    "message" -> 5,
    "model" -> 6,
    "multipart" -> 7,
    "text" -> 8,
    "video" -> 9
  )

  /**
   * 获取类型对应的id
   */
  def typeId(mediaType: MediaType): Option[Int] = typeIdMap.get(mediaType.`type`)

  /**
   * 获取子类型对应的id
   */
  def subtypeId(mediaType: MediaType): Option[Int] = {
    id(mediaType).map(_._2)
  }

  /**
   * 获取类型id和子类型id，返回二元组
   */
  def id(mediaType: MediaType): Option[(Int, Int)] = {
    for {
      tId <- typeId(mediaType)
      subtypeMap <- Some(subtypeIdMaps(tId)) if subtypeIdMaps isDefinedAt tId
      subtypeId <- subtypeMap.get(mediaType.subtype)
    } yield (tId, subtypeId)
  }
}

